import React from 'react'
import {
    BrowserRouter as Router,
    Route,
    Link,
    Redirect,
    Switch,
    withRouter
} from 'react-router-dom'

const LoginUtils = {
    isLogined: false,
    login: function(cb) {
        this.isLogined = true;
        cb && setTimeout(cb, 1000);
    },
    signout: function(cb) {
        this.isLogined = false;
        cb && setTimeout(cb, 1000);
    }
}

const AuthPage = withRouter(({history}) => {
    return <div>
        {LoginUtils.isLogined ? (<div>Welcome
            <button onClick={()=>{LoginUtils.signout(()=>{
            history.push('/');
        })}}>Logout
            </button>
        </div>) : <p>You are not Logined</p>}
    </div>
});

const PrivateRoute = ({component: Component, ...rest})=> {
    return <Route {...rest} render={
    (props)=>{
    if(LoginUtils.isLogined){
        return <Component {...props}/>
    }else{
        return <Redirect to={{
            pathname: '/login',
            state: {
                from: props.location,
            }
        }}/>
    }}}>
    </Route>
}

const Public = () => {
    return (<h3>公开的页面</h3>)
}

const Private = () => (<h3>非公开的页面</h3>)

class Login extends React.Component {

    componentDidMount() {
        console.log('componentDidMount');
    }

    constructor(props) {
        super(props);
        console.log('constructor');
        this.state = {
            redirectToReferrer: false
        };
        var that = this;
        this.login = function () {
            LoginUtils.login(function () {
                that.setState({
                    redirectToReferrer: true
                });
            });
        };
    }

    componentWillUnmount() {
        console.log('componentWillUnmount');
    }

    render() {
        const {from} = this.props.location.state || {from: {pathname: '/'}};
        const {redirectToReferrer} = this.state;
        if (redirectToReferrer) {
            return <Redirect to={from}/>
        }
        return <div>
            <p>需先登录才能访问: {from.pathname}</p>
            <button onClick={this.login}>Login</button>
        </div>
    }
}

const App = ()=> {
    return (<Router>
        <div>
            <AuthPage />
            <ul>
                <li><Link to="/public">public page</Link></li>
                <li><Link to="/protected">protected page</Link></li>
            </ul>
            <Route path="/public" component={Public}/>
            <Route path="/login" component={Login}/>
            <PrivateRoute path="/protected" age="12" component={Private}/>
        </div>
    </Router>)
}
export default App;

// return <Redirect to="/login"></Redirect>





